package com.sefer.dragonfly.client.core.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * 插件链条
 * 
 * @author xiaofeng 2011-11-1 下午04:40:57
 */
public class CmConsumerChain {

	/**
	 * 插件队列，从头插入，从尾取出运行，保证按配置文件从上到下运行插件,且按优先级排序
	 */
	private Queue<CmConsumer> queueCmConsumer = new PriorityQueue<CmConsumer>();

	public void addCmConsumer(CmConsumer CmConsumer) {
		queueCmConsumer.add(CmConsumer);
	}

	public CmConsumer pollCmConsumer() {
		return queueCmConsumer.poll();
	}

	public CmConsumer[] getCmConsumer(Class clazz) {
		List<CmConsumer> list = new ArrayList<CmConsumer>();
		for (CmConsumer CmConsumer : queueCmConsumer) {
			if (CmConsumer.getClass().equals(clazz)) {
				list.add(CmConsumer);
			}
		}
		CmConsumer[] array = new CmConsumer[list.size()];
		list.toArray(array);
		return array;
	}

	public void addAll(CmConsumerChain queue) {
		if (queueCmConsumer != null && queue != null) {
			queueCmConsumer.addAll(queue.queueCmConsumer);
		}
	}

	public void clear() {
		if (queueCmConsumer != null) {
			queueCmConsumer.clear();
		}
	}

	public Collection<CmConsumer> getCmConsumers() {
		if (queueCmConsumer != null) {
			return Collections.unmodifiableCollection(queueCmConsumer);
		}
		return null;
	}
}
